<?php

namespace App\Exceptions;

use App\Notifications\InvoicePaid;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\MessageBag;
use Psr\Log\LoggerInterface;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $e)
    {

        if ($this->shouldntReport($e)) {
            return;
        }

        if (method_exists($e, 'report')) {
            return $e->report();
        }
        $request=\Request::instance();
        $nickname=$request->user('member')->nickname ?? '' ;
        $markdown=">来源ip: {$request->ip()} \n".
            ">请求URL:{$request->fullUrl()} \n".
            "用户:{$nickname }".
            ">错误信息: {$e->getMessage()}\n".
            ">错误文件: {$e->getFile()} \n".
            ">错误行数: {$e->getLine()} \n";
        ding($markdown);
        try {

            $logger = $this->container->make(LoggerInterface::class);
        } catch (Exception $ex) {
            throw $e; // throw the original exception
        }

        $logger->error(
            $e->getMessage(),
            array_merge($this->context(), ['exception' => $e]
            ));
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
      /*  $member=  \App\Http\Controllers\Admin\Member\Repository\Member::find(3);
        //dd($member);
        $member->notify(new InvoicePaid('error:'.$exception->getMessage()) );*/
       if($exception instanceof WechatException) {

            if($request->ajax()){
                $msg= [
                    'code'=>'error',
                    'msg'=>$exception->getMessage()
                ];
                return response()->json($msg);
            }else{
              $error=  new MessageBag([
                  'title'=>'退款失败',
                  'message'=>$exception->getMessage(),
              ]);
              return redirect()->back()->with(compact('error'));
            }
        }

        return parent::render($request, $exception);
    }
}
